<?php

namespace app\admin\controller;

use think\Request;

use app\admin\model\Permission as PermissionModel;

class Permission extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = PermissionModel::order('id','desc')->paginate(PermissionModel::PAGESIZE);
        $data = PermissionModel::buildData();
        return $this->fetch('permission/index',compact('list','data'));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->param();
        $res = $this->validate($data,'app\admin\validate\Permission');
        if($res !== true) return $this->error($res);
        if($data['parent_id'] != 0){
            $data['level'] = PermissionModel::getLevel($data['parent_id']);
        }
        $insertRes = PermissionModel::create($data);
        if(!$insertRes){
            return $this->error('添加失败');
        }
        return $this->success('添加成功');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $data = PermissionModel::field('id,name,route,desc,parent_id')->find(intval($id));
        return json(['code' =>1, 'data' => $data]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->param();
        if(is_numeric($data['name'])){
            return $this->error('名称不能是数字');
        }
        if(!$data['name']){
            return $this->error('名称不能为空');
        }
        if(!$data['route']){
            return $this->error('路由不能为空');
        }
        if($data['parent_id'] != 0){
            $data['level'] = PermissionModel::getLevel($data['parent_id']);
        }
        unset($data['id']);
        $insertRes = PermissionModel::where('id',$id)->update($data);
        if(!$insertRes){
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $res = PermissionModel::destroy($id);
        if($res){
            return $this->success('删除成功');
        }else{
            return $this->error('删除失败');
        }
    }

    public function deletes(){
        $ids = input('get.ids');
        if(empty($ids) || !is_array($ids)){
            return $this->error('请选择要删除的数据');
        }
        $res = PermissionModel::destroy($ids);
        if($res){
            return json(['code' => 1,'msg' => '删除成功','data' => $ids]);
        }else{
            return $this->error('删除失败');
        }
    }
}
